<?php

namespace App\Http\Controllers\Backend\Message;

use App\Events\MessageSendEvent;
use App\Http\Requests\Backend\Message\MessageSendRequest;
use App\Http\Controllers\Controller;
use App\Models\MessageSended;
use App\Models\User;
use App\Models\UserGlobal;
use Illuminate\Support\Facades\Auth;

class MessageSendController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:backend');
    }

    public function send(MessageSendRequest $request)
    {
        $user = Auth::guard('backend')->user();
        $params = $this->extractInputFromRules($request, $request->rules());
        switch ($params['type']) {
            case MessageSended::TARGET_ALL:
                $user_group = User::pluck('id')->toArray();
                break;
            case MessageSended::TARGET_APPLY:
                $user_group = UserGlobal::whereIn('global_status',MessageSended::$user_group[MessageSended::TARGET_APPLY])
                    ->pluck('uid')->toArray();
                break;
            case MessageSended::TARGET_LOAN:
                $user_group = UserGlobal::whereIn('global_status',MessageSended::$user_group[MessageSended::TARGET_LOAN])
                    ->pluck('uid')->toArray();
                break;
        }
        foreach ($user_group as $index => $user_id){
            $send['type'] = $params['type'];
            $send['template_id'] = $params['template_id'];
            $send['user_id'] = $user_id;
            $send['title'] = $params['title'];
            $send['desc'] = $params['desc'];
            $send['key_word'] = $params['key_word']??null;
            $send['url'] = $params['url']??' ';
            $send['content'] = $params['content'];
            $send['sender_id'] = $user->id;
            event(new MessageSendEvent($send));
        }
        return success([]);
    }
}
